package common

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func SendFail(ctx *gin.Context, err error) {

	if ae, ok := err.(*ApiException); ok {
		httpCode := http.StatusOK
		if ae.HttpCode > 0 {
			httpCode = ae.HttpCode
		}
		ctx.JSON(httpCode, ae.Result)
	} else {
		ctx.JSON(http.StatusOK, NewResult([]int{}).SetErrorCode(-1).SetMsg(err.Error()))
	}

}

func SendSuccess(ctx *gin.Context, res *Result) {
	ctx.JSON(http.StatusOK, res)
}

func NewResult(data any) *Result {
	return &Result{
		ErrorCode: 0,
		Msg:       "ok",
		Data:      data,
	}

}

func NewApiException(errorCode int, msg string) *ApiException {
	if errorCode == 0 {
		errorCode = -1
	}
	return &ApiException{
		Result: &Result{
			ErrorCode: errorCode,
			Msg:       msg,
			Data:      []int{},
		},
	}
}

type Result struct {
	ErrorCode int    `json:"code"`
	Msg       string `json:"msg"`
	Data      any    `json:"data"`
}

func (result *Result) SetErrorCode(errorCode int) *Result {
	result.ErrorCode = errorCode
	return result
}

func (result *Result) SetMsg(msg string) *Result {
	result.Msg = msg
	return result
}

type ApiException struct {
	HttpCode int `json:"http_code"`
	*Result
}

func (e *ApiException) Error() string {
	return e.Msg
}

func (e *ApiException) SetHttpCode(code int) *ApiException {
	e.HttpCode = code
	return e
}
